package org.shoukaiseki.aqoeous.scan;

import org.shoukaiseki.aqoeous.model.AqoeousModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;


/**
 * org.shoukaiseki.aqoeous.scan.AqoeousScan
 * <br>
 *
 * @author shoukaiseki ブログ http://www.shoukaiseki.top/<br> E-メール jiang28555@Gmail.com<br>
 * @date 2021-03-18 15:46:11<br>
 */
public class AqoeousScan  implements ApplicationListener<ContextRefreshedEvent> {

    private final static Logger logger = LoggerFactory.getLogger(AqoeousScan.class);

    private static Map<String, AqoeousModel> aqoeousModelMap = new ConcurrentHashMap();

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        Map<String,AqoeousModel> mapTemp = new ConcurrentHashMap();

        //获取全部 Aqoeous注解的Bean
        Map<String, Object> beans = event.getApplicationContext().getBeansWithAnnotation(Aqoeous.class);

        Set<Map.Entry<String, Object>> entries = beans.entrySet();//遍历Bean

        Iterator<Map.Entry<String, Object>> iterator = entries.iterator();
        while(iterator.hasNext()){
            Map.Entry<String, Object> map = iterator.next();
            String beanName = map.getKey();
            logger.info("--------------bean="+ beanName);
            Class<?> aClass = map.getValue().getClass();

            logger.info("aClass={}",aClass);

            Aqoeous aqoeous;


            aqoeous= AnnotationUtils.findAnnotation(aClass,Aqoeous.class);

            String qoname=aqoeous.name();
            if(StringUtils.isEmpty(qoname)){
                //首字母小写
                qoname= StringUtils.uncapitalize(aqoeous.qoClass().getSimpleName());
            }

            AqoeousModel aqoeousModel=new AqoeousModel(qoname,aqoeous.qoClass(),beanName);

            logger.debug("qoname={},class={}",qoname,aqoeous.qoClass());

            mapTemp.put(qoname,aqoeousModel);

        }
        //只读map
        // Collections.unmodifiableMap 相当于是个代理,代理map线程安全就行
        aqoeousModelMap= Collections.unmodifiableMap(mapTemp);

    }

    public static Map<String, AqoeousModel> getAqoeousModelMap() {
        return aqoeousModelMap;
    }
}

